


//初始化
	var swichVal=localStorage.getItem("swichVal");
	var csdnVal=localStorage.getItem("csdnVal");
	var cnblogsVal=localStorage.getItem("cnblogsVal");
	var zhihuVal=localStorage.getItem("zhihuVal");
if(swichVal==null){
	alert("1");
	localStorage.setItem("swichVal",true);
}
if(csdnVal==null){
	alert("2");
	localStorage.setItem("csdnVal",true);
}
if(cnblogsVal==null){
	alert("3");
	localStorage.setItem("cnblogsVal",true);
}
if(zhihuVal==null){
	alert("4");
	localStorage.setItem("zhihuVal",true);
}



var endStr="#betterbaidu";
chrome.webRequest.onBeforeRequest.addListener(details => {
	
	swichVal=localStorage.getItem("swichVal");
	csdnVal=localStorage.getItem("csdnVal");
	cnblogsVal=localStorage.getItem("cnblogsVal");
	zhihuVal=localStorage.getItem("zhihuVal");
	
	
	
	if(swichVal!="true"){
		//alert("过滤关闭了");
		return;
	}
	
	
	
	var thisUrl=details.url;
	var wd= getWd(thisUrl);
	//alert(wd);
	var tabId=details.tabId;
	//console.log(details);
	
	var addkeyword="";
	if(csdnVal=="true"){
		addkeyword+=" -csdn";
	}
	if(cnblogsVal=="true"){
		addkeyword+=" -博客园";
	}
	if(zhihuVal=="true"){
		addkeyword+=" -知乎";
	}
	
	
	
	if(thisUrl.indexOf("baidu.com")>-1 && wd!="" && !thisUrl.endsWith(endStr)){
		var newUrl=getNewUrl(thisUrl,addkeyword);
		if(details.type=="main_frame"){
			chrome.tabs.update(tabId,{
				url:newUrl
			});
		}
		else if(details.type=="xmlhttprequest")
		{
			return {
				redirectUrl:newUrl
			};
		}
		
	}
	
	
}, {urls: ["<all_urls>"],"types":["main_frame","xmlhttprequest"]}, ["blocking"]);




function getWd(thisUrl){
	if(thisUrl.indexOf("?")==-1){
		return "";
	}
	var query = thisUrl.split('?')[1];
	       var vars = query.split("&");
	       for (var i=0;i<vars.length;i++) {
	               var pair = vars[i].split("=");
	               if(pair[0] == "wd")
					{
						//alert("关键词为："+pair[1]);
						return pair[1];
					}
	       }
		   //alert("为获取到关键词");
	       return "";
}


function getNewUrl(thisUrl,addkeyword){
	if(thisUrl.indexOf("?")==-1){
		return "";
	}
	
	var newUrl=thisUrl.split('?')[0]+"?";
	
	var query = thisUrl.split('?')[1];
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
	    var pair = vars[i].split("=");
	    if(pair[0] == "wd")
			{
				//alert("关键词为："+pair[1]);
				//return pair[1];
				newUrl+=pair[0]+"="+pair[1]+addkeyword;
			}else{
				newUrl+=pair[0]+"="+pair[1];
			}
			newUrl+="&";
	}
	
	return newUrl+endStr;
}
